package com.pdg.dungeondelver.defaulttheme.builders;

import java.util.Iterator;

import com.pdg.dungeondelver.client.constants.BuilderConstants;
import com.pdg.dungeondelver.client.constants.GameConstants;
import com.pdg.dungeondelver.client.constants.PropertyGroupConstants;
import com.pdg.dungeondelver.engine.AtlasCell;
import com.pdg.dungeondelver.engine.Layer;
import com.pdg.dungeondelver.engine.LayerBuilder;
import com.pdg.dungeondelver.engine.LayerCell;
import com.pdg.dungeondelver.engine.LayerColumn;
import com.pdg.dungeondelver.engine.LayerColumnBuilder;
import com.pdg.dungeondelver.engine.LayerDirections;

public class DefaultLayerBuilder implements LayerBuilder{

	private void populateNeighbors(Layer theLayer){
		Iterator<Integer> columnIterator = theLayer.keySet().iterator();
		while(columnIterator.hasNext()){
			Integer currentColumn = columnIterator.next();
			Iterator<Integer> rowIterator = theLayer.get(currentColumn).keySet().iterator();
			while(rowIterator.hasNext()){
				Integer currentRow = rowIterator.next();
				for(LayerDirections direction:LayerDirections.getDirections()){
					Integer nextColumn = direction.getNextColumn(currentColumn,currentRow);
					Integer nextRow = direction.getNextRow(currentColumn,currentRow);
					LayerColumn nextLayerColumn = theLayer.get(nextColumn);
					if(nextLayerColumn!=null){
						LayerCell nextLayerCell = theLayer.get(nextColumn).get(nextRow);
						if(nextLayerCell!=null){
							theLayer.get(currentColumn).get(currentRow).setNeighbor(direction, nextLayerCell);
						}
					}
				}
			}
		}
	}
	
	@Override
	public Layer build(AtlasCell theCell) {
		Layer layer = new Layer(theCell);
		Integer columns = theCell.getConfiguration().getPropertyGroups().get(PropertyGroupConstants.GAME_CONSTANTS).<Integer>get(GameConstants.LAYER_COLUMNS);
		LayerColumnBuilder builder = theCell.getConfiguration().getPropertyGroups().get(PropertyGroupConstants.BUILDERS).<LayerColumnBuilder>get(BuilderConstants.LAYER_COLUMN_BUILDER);
		for(Integer index=0;index<columns;++index){
			layer.put(index, builder.build(layer));
		}
		populateNeighbors(layer);
		return layer;
	}

}
